package com.example.elasticsearch.controller;

import org.elasticsearch.client.IndicesClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
public class ControllerAdvice {
    @InitBinder
    public void date(WebDataBinder binder){
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class,new CustomDateEditor(dateFormat,true));
    }

    @Autowired
    RestHighLevelClient restHighLevelClient;
    String INDEX="test-create-index1";

    @RequestMapping("/test")
    @ResponseBody
    public String test() throws IOException {
        String result;
        //一切索引的操作都在 IndicesClient类中，如对索引的增删改查，以及别名等
        IndicesClient indices = restHighLevelClient.indices();
        //获取索引的信息的请求
        GetIndexRequest getIndexRequest = new GetIndexRequest(INDEX);
        //判断是否存在索引
        boolean exists = indices.exists(getIndexRequest, RequestOptions.DEFAULT);
        System.out.println(exists);
        if(exists)
            result="存在";
        else
            result="不存在";
        return result;
    }

}
